package com.xht.transaction.data;

import com.xht.transaction.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;

/**
 * dao层
 */
@Repository
public class UserData {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     * @param userName
     * @return
     */
    public Boolean insert(String userName){
        int result = jdbcTemplate.update("insert into user (user_name) value (?)", userName);
        return result > 0 ? Boolean.TRUE : Boolean.FALSE;
    }

    /**
     * 更新
     * @param id
     * @param userName
     * @return
     */
    public Boolean update(Integer id ,String userName){
        String sql = "update user set user_name = ? where id = ?";
        int result = jdbcTemplate.update(sql, userName, id);
        return result > 0 ? Boolean.TRUE : Boolean.FALSE;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public Boolean  delete(Integer id){
        String sql = "delete from user where id = ?";
        int result = jdbcTemplate.update(sql,  id);
        return result > 0 ? Boolean.TRUE : Boolean.FALSE;
    }

    /**
     * 单个查询
     * @param id
     * @return
     */
    public UserDTO findId(Integer id){
        String sql = "select * from user where id = ?";
        UserDTO userDTO = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(UserDTO.class), id);
        return userDTO;
    }

    /**
     * 按多个id查询
     * @param idList
     * @return
     */
    public List<UserDTO> findByIdList(List<Integer> idList){
        if (idList == null || idList.isEmpty()) {
            return Collections.emptyList();
        }

        String sql = "SELECT * FROM user WHERE id IN (";
        // 生成逗号分隔的占位符（?, ?, ?）
        String placeholders = String.join(",", Collections.nCopies(idList.size(), "?"));
        sql += placeholders + ")";

        // 关键：将List转换为数组并传递参数
        Object[] params = idList.toArray(); // 将List转为数组

        // 执行查询（注意params数组会自动展开匹配占位符）
        List<UserDTO> userDTOList = jdbcTemplate.query(
                sql,
                new BeanPropertyRowMapper<>(UserDTO.class),
                params // 传递参数数组
        );
        return userDTOList;
    }

}
